﻿// GDRoundImageView.cpp
//

#include "GDRoundImageView.h"
#include "../GdDefine.h"

GDRoundImageView::GDRoundImageView()
	: m_pImageView(NULL)
	, m_pBlendView(NULL)
	, m_pClippingView(NULL)
	, m_pStencilView(NULL)
{
}

GDRoundImageView::~GDRoundImageView()
{
}

GDRoundImageView* GDRoundImageView::createWithFrame(const CCRect& frame)
{
	GDRoundImageView *pRet = new GDRoundImageView();
	if (pRet && pRet->initWithFrame(frame))
	{
		pRet->autorelease();
		return pRet;
	}
	CC_SAFE_DELETE(pRet);
	return NULL;
}

GDRoundImageView* GDRoundImageView::createWithCenter(const CCRect& rect)
{
	GDRoundImageView* pRet = new GDRoundImageView();

	if (pRet && pRet->initWithCenter(rect))
	{
		pRet->autorelease();
		return pRet;
	}

	CC_SAFE_DELETE(pRet);
	return NULL;
}

bool GDRoundImageView::init()
{
	if (!CAView::init())
	{
		return false;
	}

	bool bRet = false;
	do 
	{
		m_pImageView = CommonUrlImageView::createWithFrame(CCRectZero);
		CC_BREAK_IF(!m_pImageView);
		m_pBlendView = CAImageView::createWithFrame(CCRectZero);
		CC_BREAK_IF(!m_pBlendView);
		m_pClippingView = CAClippingView::create();
		CC_BREAK_IF(!m_pClippingView);
		m_pStencilView = CADrawView::create();
		CC_BREAK_IF(!m_pStencilView);

		m_pClippingView->setStencil(m_pStencilView);
		m_pClippingView->addSubview(m_pImageView);
		this->addSubview(m_pClippingView);
		this->addSubview(m_pBlendView);

		bRet = true;
	} while (0);
	
	return bRet;
}

void GDRoundImageView::setContentSize(const CCSize & size)
{
	CCRect rect(0, 0, size.width, size.height);

	if (m_pImageView) {
		m_pImageView->setFrame(rect);
	}
	if (m_pBlendView) {
		m_pBlendView->setFrame(rect);
	}
	if (m_pClippingView) {
		m_pClippingView->setFrame(rect);
	}
	if (m_pStencilView) {
		m_pStencilView->setCenterOrigin(CCPoint(size.width*0.5f, size.height*0.5f));

		CCPoint cir[720];
		float radius = min(size.width, size.height) * 0.5f - _ds(1);
		for (int i = 0; i < 720; i++)
		{
			float x = cosf(i * M_PI / 180.f) * radius;
			float y = sinf(i * M_PI / 180.f) * radius;

			cir[i] = CCPoint(x, y);
		} // end for i

		m_pStencilView->clear();
		m_pStencilView->drawPolygon(cir, sizeof(cir)/sizeof(cir[0]), ccc4f(0, 0, 0, 1), 0, ccc4f(0, 0, 0, 0));
	}
}

void GDRoundImageView::setImage(CAImage *pImage)
{
	CC_RETURN_IF(!m_pImageView);
	m_pImageView->setImage(pImage);
}

void GDRoundImageView::setImageUrl(const string &url)
{
	CC_RETURN_IF(!m_pImageView);
	m_pImageView->setUrl(url);
}

void GDRoundImageView::setBlendImage(CAImage *pImage)
{
	CC_RETURN_IF(!m_pBlendView);
	m_pBlendView->setImage(pImage);
}
